#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   file.py
@Time    :   2024-07-24 16:17:52
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   文件上传与下载
'''
import os
import shutil

from fastapi import APIRouter, Security, File, UploadFile
from fastapi.responses import FileResponse

from ..dependencies.jwt import Authorization
from ..config import config

router = APIRouter(prefix="/file", tags=["file-controller"], dependencies=[Security(Authorization)])

UPLOAD_DIR = config.upload_folder
os.makedirs(UPLOAD_DIR, exist_ok=True)

@router.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    file_path:str = os.path.join(UPLOAD_DIR, file.filename) # type: ignore
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    return {"filename": file.filename}

@router.get("/downloadfile/{filename}")
async def download_file(filename: str):
    file_path: str = os.path.join(UPLOAD_DIR, filename)
    return FileResponse(file_path, media_type="application/octet-stream", filename=filename)
